package cn.hpclub.server.controller.admin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.model.ServiceReservation;
import cn.hpclub.server.service.BroadbandorderService;
import cn.hpclub.server.util.InterfaceUtil;

public class BroadbandorderController extends BaseAdminController<ServiceReservation>{
    private static Logger       log         = LoggerFactory.getLogger(BroadbandorderController.class);
    private static final String ORG_LIST    = "orgList";
    private static final String ORG_ID      = "org_id";
    private static final String CREATE_DATE = "create_date";
    private static final String START_DATE  = "start_date";
    private static final String END_DATE    = "end_date";

    /**
     * @Title: 获取角色列表
     */
    public void list(){
        String isExport = getPara("isExport");

        int defaultOrgId = iniOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }
        if(searchInfo.get(CREATE_DATE) == null){
            try{
                setDateParam(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }

        if("1".equals(isExport)){
            export(searchInfo);
        } else{
            query(searchInfo);
        }
    }

    private void export(ConcurrentHashMap<String, String> searchInfo){
        List<Record> listExport = BroadbandorderService.service.getListExport(searchInfo);

        PoiRender excel = PoiRender.me(listExport);
        String[] headesExport = BroadbandorderService.headesExport;
        String[] columnsExport = BroadbandorderService.columnsExport;

        render(excel.sheetName("预约信息报表").headers(headesExport).columns(columnsExport).fileName(generateFileName()));
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String curTime = sdf.format(date);
        String fileName = "report-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        return fileName;
    }

    private void query(ConcurrentHashMap<String, String> searchInfo){
        findByPageBroadbandReservation(searchInfo);
        setAttrs(searchInfo);
        render("/admin/broadband_order.tpl");
    }

    private void setDateParam(ConcurrentHashMap<String, String> searchInfo) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new java.util.Date());
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(endDate));
        c.add(Calendar.MONTH, -1); // 得到前一个月
        String startDate = sdf.format(c.getTime());
        String createDate = startDate + "|" + endDate;

        log.info("createDate =" + createDate);
        searchInfo.put(START_DATE, startDate);
        searchInfo.put(END_DATE, endDate);
        searchInfo.put(CREATE_DATE, createDate);
    }

    @SuppressWarnings("static-access")
    private void findByPageBroadbandReservation(ConcurrentHashMap<String, String> searchInfo){
        String select = new BroadbandorderService().service.getListSqlSelect();
        String sqlExceptSelect = new BroadbandorderService().service.getSqlExceptSelect(searchInfo);
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        Page<ServiceReservation> pager = ServiceReservation.dao.paginate(pageNumber, getParaToInt(PAGE_SIZE, 10),
                                                                         select, sqlExceptSelect);
        /* 删除最后一页所有数据后，显示最后一页前一页 */
        if(pager.getPageNumber() > 1 && pager.getList().size() == 0){
            pager = ServiceReservation.dao.paginate(pageNumber - 1, getParaToInt(PAGE_SIZE, 10), select,
                                                    sqlExceptSelect);
        }
        setAttr(PAGER, pager);
    }

    private int iniOrgTree(){
        List<Entry<String, String>> orgList = InterfaceUtil.getOrgList();
        setAttr(ORG_LIST, orgList);
        if(orgList.size() > 0){
            return Integer.parseInt(orgList.get(0).getValue());
        } else{
            return 0;
        }
    }

    /**
     * @Title: 更新数据
     */
    @Before({ Tx.class })
    public void update(){
        ServiceReservation bdorder = new ServiceReservation();
        bdorder.set("id", getParaToInt("bdorder.id"))// 宽带订单ID
                .set("gender", getParaToInt("bdorder.gender", 0))// 客户性别 0先生 1女士
                .set("customer_name", getPara("bdorder.customer_name", ""))// 客户姓名
                .set("telephone", getPara("bdorder.telephone", ""))// 客户电话
                .set("city", getPara("bdorder.city", ""))// 城市，默认成都
                .set("install_address", getPara("bdorder.address", ""))// 地址
                .set("reservation_state", getParaToInt("bdorder.reservation_state"))// 预约状态,1待审核,2审核通过,3审核不通过,4结单
                .set("create_date", getPara("bdorder.create_date", "")).set("boss_no", getPara("bdorder.order_no", ""));// 订单号，目前随便输入，以后由移动传入
        // 如果是结单状态,写入接单时间
        if(getParaToInt("bdorder.reservation_state") == 4){
            bdorder.set("end_date", new Date());
        } else{
            Db.update("UPDATE service_reservation SET end_date=NULL where id=?", getParaToInt("bdorder.id"));
        }
        bdorder.update();

        redirect("/broadbandorder/list");
    }

    /**
     * @Title:编辑
     */
    public void edit(){
        int id = getParaToInt("id");
        String sql = "select sr.id as id, customer_name, sr.city, area, install_address as address, gender, telephone, reservation_state, date_format(create_date,'%Y-%m-%d %H:%i:%s') as create_date, manager_id, sr.boss_no as order_no, bd.introduction, bd.price, bd.period, mo.name as saler_name, mo.mobile as saler_mobile from service_reservation sr left join broadband bd on sr.broadband_id=bd.id left join member_org mo on sr.user_id=mo.id where sr.id="
                + "?";
        List<Record> records = Db.find(sql, id);
        setAttr("bdorder", records.get(0));
        render("/admin/broadband_order_input.tpl");
    }

    // 删除
    @Before(Tx.class)
    public void delete(){
        String[] ids = getParaValues("ids");
        log.info("ids=" + ids);
        if(ids == null || ids.length == 0){
            ajaxJsonErrorMessage("删除失败，无选中项！");
            return;
        }
        if(ServiceReservation.dao.delete(ids)){
            ajaxJsonSuccessMessage("删除成功！");
        } else{
            ajaxJsonErrorMessage("删除失败！");
        }
    }
}
